package com.aspire.curator.api;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.retry.RetryNTimes;
import org.apache.curator.retry.RetryOneTime;
import org.apache.curator.retry.RetryUntilElapsed;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;

/**
 * Curator客户端框架 创建节点
 *
 * @author JustryDeng
 * @date 2018/11/22 17:24
 */
public class CreateNodeDemo {

    /**
     * 每3秒重连一次 移动重连3次
     */
    private static RetryPolicy retryPolicy = new RetryNTimes(3, 1000);


    /**
     * 3秒后重连一次 只重连一次
     */
//    private static RetryPolicy retryPolicy = new RetryOneTime(3000);


    /**
     * 每3秒重连一次 总等待时间超过10秒后 停止重连
     *
     */
//    private static RetryPolicy retryPolicy = new RetryUntilElapsed(10000,3000);

    /**
     * 随着重连次数的增加 重连间隔的时间也会变长
     * 时间间隔 = baseSleepTimeMs * Math.max(1, random.nextInt(1 << (retryCount + 1)))
     */
//    private static RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
    public static void main(String[] args) throws Exception {

        CuratorFramework client = CuratorFrameworkFactory.builder().connectString("127.0.0.1:2181")
                //会话超时时间
                .sessionTimeoutMs(5000)
                //重连机制 超时之后 3秒进行一次重连
                .retryPolicy(retryPolicy)
                //命名空间
                .namespace("create")
                .build();
//        CuratorFramework client = CuratorFrameworkFactory.newClient("127.0.0.1:2181", 5000,
//                5000, retryPolicy);
        // 启动客户端
        client.start();


        //输出是否启动成功
        System.out.println(client.isStarted());

        // 其中creatingParentsIfNeeded()的作用为:如果要创建的节点的父节点不存在，那么会先创建父节点，再创建该节点
        String newNode = client
                .create()
                .creatingParentsIfNeeded()
                //节点类型
                .withMode(CreateMode.PERSISTENT)
                .withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE)
                .forPath("/a_node/a_1", "a_1".getBytes());
        System.out.println("新创建的节点是:" + newNode);
    }






}